/**
 * Created by adeline on 2017/6/8.
 */
import util from './utils'
import axios from 'axios'

/**
 * 远程接口数据访问对象
 *
 * @class common.remoteDAO
 */
const RemoteDAO = {}
const Bridge = window.Bridge || {}
const decrypt = window.decrypt || {}

/**
 * 圈子消息列表
 * @param  {json} param
 * @return {function}        回调
 */
RemoteDAO.queryDynamics = function (params = {
  pageNum: 1,
  pageSize: 10,
  maxId: 0
}) {
  return new Promise((resolve, reject) => {
    const paramData = {
      funcType: 'queryDynamics',
      pageNum: params.pageNum + '',
      pageSize: params.pageSize + ''
    }
    if (parseInt(params.maxId, 10) !== 0) {
      paramData.maxId = params.maxId
    }
    if (util.getUserCode()) {
      paramData.userCode = util.getUserCode()
    }
    const param = util.setToken(paramData)
    const bridgeParam = {
      id: 'circle',
      tranCode: 'GT1001',
      jsToken: 'GT1001',
      isEncrypt: 'false',
      transmitMode: 'get',
      callback: function (response) {
        if (response.error === '1') {
          console.error('queryDynamics-获取圈子的消息-error:', response)
          reject(new Error('query dynamics error' + JSON.stringify(response)))
        } else {
          const result = decrypt.json2(response.data)
          const json = JSON.parse(result)
          console.info('queryDynamics-获得圈子的消息-:', JSON.stringify(json))
          resolve(Object.assign({}, response, { data: json }))
        }
      }
    }
    const finalParam = util.setTouristParam(param, bridgeParam)
    Bridge.callByJS(finalParam)
  })
}

/**
 * 访问用户配置圈子权限的信息
 * @param param
 *        usercode 用户代码
 * @param callback
 */
RemoteDAO.queryUserConfig = function (param) {
  return new Promise(function (resolve, reject) {
    Bridge.callByJS({
      'id': 'circle',
      'tranCode': 'GT1001',
      'jsToken': 'GT1001',
      'isEncrypt': 'false',
      'transmitMode': 'get',
      'param': {
        'funcType': 'queryUserConfig',
        'userCode': util.getUserCode()
      },
      'localParameter': {},
      callback: function (response) {
        if (response.error === '1') {
          console.log('queryUserConfig-访问用户配置圈子权限的信息-error:', response)
          reject(new Error('query user config error' + JSON.stringify(response)))
        } else {
          console.log('queryUserConfig-访问用户配置圈子权限的信息-data:', response)
          let result = decrypt.json2(response.data)
          let json = JSON.parse(result)
          resolve(Object.assign({}, response, { data: json }))
        }
      }
    })
  })
}

/**
 * 对消息进行订阅/关闭的接扣
 * @param  {object} param 参数
 * @return {promise}
 */
RemoteDAO.updateUserConfig = function (param = {
  msgType: 'JYB_OF_FOLLOWEES', // 消息类型
  funcType: 'disable' // 订阅enable,关闭disable
}) {
  return new Promise(function (resolve, reject) {
    Bridge.callByJS({
      'id': 'circle',
      'tranCode': 'GT1001',
      'jsToken': 'GT1001',
      'isEncrypt': 'false',
      'transmitMode': 'get',
      'param': {
        'msgType': param.msgType,
        'funcType': param.funcType,
        'userCode': util.getUserCode()
      },
      'localParameter': {},
      callback: function (response) {
        if (response.error === '1') {
          console.log('JYB_OF_FOLLOWEES-消息关闭，打开-error:', response)
          reject(new Error('JYB_OF_FOLLOWEES error' + JSON.stringify(response)))
        } else {
          let result = decrypt.json2(response.data)
          let json = JSON.parse(result)
          resolve(Object.assign({}, response, { data: json }))
          console.log('JYB_OF_FOLLOWEES-消息关闭，打开-data:', response)
        }
      }
    })
  })
}

/**
 * 对消息进行点赞/取消点赞的接扣
 * @param  {object} param 参数
 * @return {promise}
 */
RemoteDAO.voteMessage = function (param = {
  targetId: '1000', //  目标对象id，消息id（可以使用id或msgId某一个，由客户端和服务端约定）
  funcType: 'voteUp' // 功能名称     voteUp 、 voteCancel
}) {
  return new Promise(function (resolve, reject) {
    Bridge.callByJS({
      id: 'circle',
      tranCode: 'GT1002',
      jsToken: 'GT1002',
      isEncrypt: 'false',
      transmitMode: 'get',
      param: {
        userId: util.getUserCode(),
        targetId: param.targetId + '',
        funcType: param.funcType + ''
      },
      localParameter: {},
      callback: function (response) {
        if (response.error === '1') {
          console.log('voteMessage-点赞，取消点赞-error:', response)
          reject(new Error('JYB_OF_FOLLOWEES error' + JSON.stringify(response)))
        } else {
          let result = decrypt.json2(response.data)
          let json = JSON.parse(result)
          resolve(Object.assign({}, response, { data: json }))
          console.log('voteMessage-点赞，取消点赞-data:', response)
        }
      }
    })
  })
}

/**
 * 点击moment增加浏览数
 * @param  {object} param 参数
 * @return {promise}
 */
RemoteDAO.browseMoment = function (param = {
  targetId: '1000'
}) {
  return new Promise(function (resolve, reject) {
    Bridge.callByJS({
      id: 'circle',
      tranCode: 'GT1002',
      jsToken: 'GT1002',
      isEncrypt: 'false',
      transmiteMode: 'get',
      param: {
        userId: util.getUserCode(),
        targetId: param.targetId,
        funcType: 'browseIncrease'
      },
      localParameter: {},
      callback: function (response) {
        if (response.error === '1') {
          console.log('browseIncrease-浏览圈子-error:', response)
          reject(new Error(JSON.stringify(response)))
        } else {
          const result = decrypt.json2(response.data)
          const json = JSON.parse(result)
          resolve(Object.assign({}, response, { data: json }))
        }
      }
    })
  })
}

/**
 * 登录
 * @param callback
 */
RemoteDAO.callNativeLogin = function () {
  const _this = this
  return new Promise(function (resolve, reject) {
    Bridge.callByJsUrl('gtjanrng://register', response => {
      if (parseInt(response.error, 10) === 1) {
        reject(new Error(JSON.stringify(response)))
      } else {
        const userCode = response.data.user_code
        const nickName = response.data.nick_name

        localStorage.setItem('userCode', userCode)
        localStorage.setItem('nickName', nickName)

        if (Number(response.data.registerFlag) === 1) {
          _this.initRegisterSucc()
        } else {
          resolve(response)
        }
      }
    }, 'gtjanrng')
  })
}

/**
 * 初次注册成功弹窗
 */
RemoteDAO.initRegisterSucc = function () {
  const wrapTag = document.createElement('div')
  wrapTag.className = 'register_succ-wrap'
  wrapTag.style.position = 'fixed'
  wrapTag.style.width = '100%'
  wrapTag.style.backgroundColor = 'rgba(0, 0, 0, 0.6)'
  wrapTag.style.overflowY = 'scroll'
  wrapTag.style.display = 'block'
  wrapTag.style.top = '0'
  wrapTag.style.bottom = '0'
  wrapTag.style.zIndex = '1099'

  const imgTag = document.createElement('img')
  imgTag.src = 'https://dl.app.gtja.com/nrng/shareimages/register_succ.png'
  imgTag.style.width = '100%'
  wrapTag.appendChild(imgTag)

  const btnWrap = document.createElement('div')
  btnWrap.style.textAlign = 'center'
  const btnTag = document.createElement('div')
  btnTag.style.fontSize = '1.7rem'
  btnTag.style.color = 'white'
  btnTag.style.borderRadius = '1rem'
  btnTag.style.padding = '6px 10px'
  btnTag.style.backgroundColor = 'rgba(250, 179, 67, 1)'
  btnTag.style.minWidth = '60%'
  btnTag.style.display = 'inline-block'
  btnTag.innerHTML = '好的，我也去～'
  btnTag.onclick = function () {
    wrapTag.style.display = 'none'
    window.location.reload(true)
  }

  btnWrap.appendChild(btnTag)
  wrapTag.appendChild(btnWrap)
  document.body.appendChild(wrapTag)
}

/**
 *  分享
 * @param title     分享题目
 * @param content   分享的内容
 * @param linkurl   链接
 * @param moments 表示分享到朋友圈是使用title还是content,或是都拼在一起  title/content/all
 */
RemoteDAO.share = function (title, content, linkurl, moments, icon) {
  // const shareid = LocalDAO.getShareid() || CommonUtil.getUrlParam('shareid')
  const shareid = ''
  window.location.href = 'gtjayyznormal://yyzShare?activitycode=201611_NRNG&title=' +
    title + '&icon=' + icon + '&content=' + content + '&moments=' + moments +
    '&linkurl=' + linkurl + '&shareid=' + shareid + '&activitycode=201611_NRNG'
}

/**
 * 将需要分享的数据传送到后台接口
 * @param pagename
 * @param callback
 * @useless
 */
RemoteDAO.sendShareData = function (pagename) {
  const nickname = localStorage.getItem('nickname')
  let usercode = nickname === ''
    ? parseInt(Math.random() * 100000)
    : localStorage.getItem('userCode')
  const shareContent = localStorage.getItem(pagename)
  const url = 'https://dl.app.gtja.com/yyz/data/api/niurenshare/share'
  return axios.post(url, {
    usercode,
    type: pagename,
    content: shareContent
  })
}

export default RemoteDAO
